#!/bin/bash
# chkconfig: 345 99 01
# description: zstack test agent
### BEGIN INIT INFO
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
### END INIT INFO

export PATH=/sbin:/bin:/usr/sbin:/usr/bin

DIR=$(dirname $(readlink -f "$0"))
SERVER=/var/lib/zstack/testagent/testagent
HOMDIR=/home/testagent
LOGFILE=$HOMDIR/testagent.log
BOOTLOG=$HOMDIR/testagentstartup.log

if [ $# -eq 0 ]; then
    echo "usage: $0 [start|stop|restart|status]"
    exit 1
fi

err_exit() {
    echo $1
    exit 1
}

LOG_DIR=`dirname $LOGFILE`; mkdir -p $LOG_DIR
id -u vyos >/dev/null 2>/dev/null
if [ $? -eq 0 ]; then
    ETH0_IP=`ip route | grep eth0 | awk '{printf $9}'`
    if [ x$ETH0_IP == "x" ]; then
       err_exit "unable to get the IP of eth0"
    fi
fi

get_pid() {
    pgrep testagent
}

check_status() {
    pid=$(get_pid)

    if [ x$pid = x"" ]; then
        # stopped
        return 1
    else
        # running
        return 0
    fi
}

server_status() {
    check_status
    ret=$?
    if [ $ret -eq 0 ]; then
        pid=$(get_pid)
        echo "zstack test agent [PID:$pid] is running"
    elif [ $ret -eq 1 ]; then
        echo "zstack test agent is stopped"
    fi

    exit $ret
}

do_start() {
    old_pid=$1
    if [ x$old_pid != x"" ]; then
        # kill hanged daemon
        kill -9 $old_pid
    fi

    id -u vyos >/dev/null 2>/dev/null
    if [ $? -eq 0 ]; then
    	chown -R vyos:users $HOMDIR
        chmod a+x $SERVER
        su - vyos -c "nohup $SERVER -type vyos -ip $ETH0_IP -port 9393 -logfile $LOGFILE >$BOOTLOG 2>&1 < /dev/null &"
	pid=$!
	iptables -I eth0.local 1 -d $ETH0_IP/32 -p tcp -m comment --comment "eth0.local-testagent" -m tcp --dport 9393 -j RETURN
    else
        chmod a+x $SERVER
        nohup $SERVER -ip 0.0.0.0 -port 9393 -logfile $LOGFILE >$BOOTLOG 2>&1 < /dev/null &
        pid=$!
    fi
    echo ${pid} > /var/run/zstack/zstacktestagent.pid

    sleep 1
    check_status > /dev/null || err_exit "unable to start zstack test agent"

    exit 0
}

start_server() {
    check_status
    ret=$?
    if [ $ret -eq 0 ]; then
        pid=$(get_pid)
        echo "zstack test agent [PID:$pid] is running already"
    elif [ $ret -eq 1 ]; then
        do_start ""
    fi
}

do_stop() {
    pid=$(get_pid)
    if [ x$pid != x"" ]; then
        kill -SIGINT $pid
        sleep 1
        kill -SIGTERM $pid 2> /dev/null
        while `kill -0 $pid`; do
            sleep 1
        done
    fi
}

stop_server() {
    check_status
    ret=$?
    if [ $ret -ne 0 ]; then
        echo "zstack test agent stopped already"
	return
    fi

    do_stop
}

CMD="$1"
case "$CMD" in
    start) start_server ;;
    stop) stop_server ;;
    status) server_status ;;
    restart) stop_server; start_server;;
esac
